import 'package:ble_helper_plugin/library.dart';
import 'package:ble_helper_plugin/src/handler_bluetooth_device.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class ServiceCharacteristicsAdapter<T extends BluetoothUuidAdapterBase> {
  final BluetoothDevice device;
  final List<T> bluetoothAdapters;
  final List<BluetoothService> services;

  // 构造函数
  ServiceCharacteristicsAdapter(
    this.device,
    this.bluetoothAdapters,
    this.services,
  );

  // 获取匹配的适配器
  Future<HandlerBluetoothDevice> getMatchAdapter() async {
    if (bluetoothAdapters.isEmpty) {
      throw Exception('No adapters available');
    }
    // 寻找适配器
    return _findAdapters().then((adapter) => adapter.entries.first.value);
  }

  // 查找蓝牙适配器服务和特征
  Future<Map<T, HandlerBluetoothDevice>> _findAdapters() async {
    Map<T, HandlerBluetoothDevice> handlerMap = {};

    for (var adapter in bluetoothAdapters) {
      var handler = HandlerBluetoothDevice();
      handler.device = device;
      try {
        // 查找通知服务
        var notifyService = await _findService(Guid(adapter.notifyServiceUuid));
        handler.bluetoothNotifyService = notifyService;

        // 查找通知特征
        var notifyCharacteristic = await _findCharacteristic(
          notifyService,
          Guid(adapter.notifyCharacteristicUuid),
        );
        handler.bluetoothNotifyCharacteristic = notifyCharacteristic;

        // 监听通知特征的变化
        var notifyStream = await _listenToCharacteristic(notifyCharacteristic);
        handler.notifyStream = notifyStream.asBroadcastStream();

        // 查找写服务
        var writeService = await _findService(Guid(adapter.writeServiceUuid));
        handler.bluetoothWriteService = writeService;

        // 查找写特征
        var writeCharacteristic = await _findCharacteristic(
          writeService,
          Guid(adapter.writeCharacteristicUuid),
        );
        handler.bluetoothWriteCharacteristic = writeCharacteristic;

        // 效验设备连接是否成功
        if (handler.bluetoothNotifyService == null ||
            handler.bluetoothNotifyCharacteristic == null ||
            handler.bluetoothWriteService == null ||
            handler.bluetoothWriteCharacteristic == null) {
          throw Exception('Device connection failed for adapter');
        }
        handlerMap[adapter] = handler;
        // 连接成功后，退出循环
        break;
      } catch (e) {
        // 如果失败，继续尝试下一个适配器
        debugPrint('Not ${adapter.runtimeType}: ${e.toString()}');
        continue;
      }
    }

    if (handlerMap.isEmpty) {
      throw Exception('Failed to connect to any adapter');
    }
    return handlerMap;
  }

  // 查找服务
  Future<BluetoothService> _findService(Guid serviceUuid) {
    return Future(
      () => services.firstWhere(
        (service) {
          return service.uuid == serviceUuid &&
              service.characteristics.isNotEmpty;
        },
        orElse: () => throw Exception('Service not found'),
      ),
    );
  }

  // 查找特征值
  Future<BluetoothCharacteristic> _findCharacteristic(
    BluetoothService service,
    Guid characteristicUuid,
  ) {
    return Future(
      () => service.characteristics.firstWhere(
        (c) {
          return c.uuid == characteristicUuid;
        },
        orElse: () => throw Exception('Characteristic not found'),
      ),
    );
  }

  // 订阅通知
  Future<Stream<List<int>>> _listenToCharacteristic(
      BluetoothCharacteristic characteristic) async {
    try {
      await characteristic.setNotifyValue(true);
      return characteristic.lastValueStream;
    } catch (e) {
      throw Exception('Notification setup failed: ${e.toString()}');
    }
  }
}
